package com.abocode.aichat.app.vo;

import com.abocode.aichat.app.constant.ErrorCode;
import com.abocode.aichat.app.exception.ContextRuntimeException;
import com.abocode.aichat.app.utils.EncryptionUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by guanxf on 2016/1/7.
 */
public class RereadHttpServletRequestWrapper  extends HttpServletRequestWrapper {

    private  String body;

    public RereadHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        int size = request.getContentLength();
        InputStream is = request.getInputStream();
        byte[] reqBodyBytes = readBytes(is, size);
        body = new String(reqBodyBytes);
        body=EncryptionUtils.fromBASE64ToDES(body);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }




    public String getBody() {
        return body;
    }

    public static final byte[] readBytes(InputStream is, int contentLen) {
        if (contentLen > 0) {
            int readLen = 0;

            int readLengthThisTime = 0;

            byte[] message = new byte[contentLen];

            try {

                while (readLen != contentLen) {

                    readLengthThisTime = is.read(message, readLen, contentLen
                            - readLen);

                    if (readLengthThisTime == -1) {// Should not happen.
                        break;
                    }

                    readLen += readLengthThisTime;
                }

                return message;
            } catch (IOException e) {
                throw new ContextRuntimeException(ErrorCode.COMM_INVALID_REQUEST, String.format("非法请求reread servlet is Exception %s",e.getMessage()));
            }
        }

        return new byte[] {};
    }

}
